package com.itqf.xiaomi.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itqf.xiaomi.dto.UsersDto;
import com.itqf.xiaomi.mapper.UserMapper;
import com.itqf.xiaomi.pojo.Users;
import com.itqf.xiaomi.service.UserService;
import com.itqf.xiaomi.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * projectName: springboot_part
 *
 * @author: 赵伟风
 * time: 2021/9/26 14:28
 * description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录业务
     *
     * @param usersDto
     * @return
     */
    @Override
    public R login(UsersDto usersDto) {

        //1.验证账号和密码不为null
        if (StringUtils.isEmpty(usersDto.getUserName())
                || StringUtils.isEmpty(usersDto.getPassword())){
            //检查账号和密码是否为null!

            return R.FAIL("账号或者密码为null!");
        }

        //2.密码加密处理
        String new_pwd = DigestUtils.md5DigestAsHex(usersDto.getPassword().getBytes());

        //3.账号和密码进行数据库验证
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", usersDto.getUserName());
        queryWrapper.eq("password", new_pwd);

        //根据账号和密码查询
        Users users = userMapper.selectOne(queryWrapper);

        //4.返回结果
        if (users == null) {

            return R.FAIL("账号或者密码错误!");
        }

        return R.OK("登录成功!", users);
    }

    /**
     * 检查用户是否可以注册业务
     *
     * @param usersDto
     * @return
     */
    @Override
    public R findUserName(UsersDto usersDto) {

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", usersDto.getUserName());

        List<Users> users = userMapper.selectList(queryWrapper);

        if (users !=null && users.size() > 0){

            return R.FAIL("账号已经存在,请更换!");
        }

        return R.OK("账号可以注册!");
    }

    /**
     * 注册业务
     *
     * @param usersDto
     * @return
     */
    @Override
    public R register(UsersDto usersDto) {

        //1.验证账号和密码不为null
        if (StringUtils.isEmpty(usersDto.getUserName())
                || StringUtils.isEmpty(usersDto.getPassword())){
            //检查账号和密码是否为null!

            return R.FAIL("账号或者密码为null!");
        }

        //2.处理下密码
        String new_pwd = DigestUtils.md5DigestAsHex(usersDto.getPassword().getBytes());

        //3.注册即可
        Users users = new Users();
        users.setUserName(usersDto.getUserName());
        users.setPassword(new_pwd);

        int rows = userMapper.insert(users);

        //4.返回结果
        if (rows == 0){

            return R.FAIL("注册用户失败!");
        }
        return R.OK("注册用户成功!");
    }
}
